#coding=utf-8
import datetime
import os
import time

from loguru import logger
from playwright.sync_api import sync_playwright
import traceback

import kuaishou.ks_common as ks_common

def group_by_period(job_list):
    job_group = {}
    period_list = list(set(map(lambda x: x['period'], job_list)))
    for period in period_list:
        filter_list = list(filter(lambda x: x['period'] == period, job_list))
        job_group[period] = filter_list
    return job_group

def ks_main(host, account_list):
    try:
        store_id_list = list(set(map(lambda x: x['storeId'], account_list)))
        logger.info('正在运行快手RPA...')
        with sync_playwright() as playwright:
            ks_func = ks_common.KS_BILL(playwright, host, 'haiwangou-key')
            for store_id in store_id_list:
                store_job_list = list(filter(lambda x: x['storeId'] == store_id, account_list))
                # 检查并登录
                ks_func.login(store_job_list[0])
                success, message = ks_func.choice_store(store_job_list[0])
                if not success:
                    log_id_list = list(set(map(lambda x: x['logId'], store_job_list)))
                    ks_func.update_log(log_id_list, message)
                    ks_func.close()
                    continue
                success, message = ks_func.check_store_id(store_job_list[0]['innerOutlineStoreCode'])
                if not success:
                    log_id_list = list(set(map(lambda x: x['logId'], store_job_list)))
                    ks_func.update_log(log_id_list, message)
                    ks_func.close()
                    continue
                # 按照周期分组，按每个周期循环运行，每跑完一个周期上传一次
                job_group = group_by_period(store_job_list)
                for period, job_list in job_group.items():
                    logger.info(f'正在下载周期【{period}】的账单')
                    param_list = []
                    file_list = []
                    logger.info(f"正在下载【{job_list[0]['platformStoreName']}】账单")
                    for item in job_list:
                        start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                        if item['accountType'] == '结算账单':
                            logger.info('开始下载结算账单...')
                            fund_flow_file = ks_func.download_bill_file(item, period)
                            if fund_flow_file is not None:
                                file_list.append(fund_flow_file)
                                dir_path, file_name = os.path.split(fund_flow_file)
                                param_list.append({'orderType': '结算账单', 'fileName': file_name, 'period': period, 'logId': item['logId'], 'startTime': start_time})
                            else:
                                param_list.append({'orderType': '结算账单', 'fileName': '无', 'period': period, 'logId': item['logId'], 'startTime': start_time})
                        start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                        if item['accountType'] == '运费险':
                            logger.info('开始下载运费险...')
                            success, file = ks_func.download_delivery_fee(item, period)
                            if success:
                                if file is not None:
                                    file_list.append(file)
                                    dir_path, file_name = os.path.split(file)
                                    param_list.append({'orderType': '运费险', 'fileName': file_name, 'period': period, 'logId': item['logId'], 'startTime': start_time})
                                else:
                                    param_list.append({'orderType': '运费险', 'fileName': '无', 'period': period, 'logId': item['logId'], 'startTime': start_time})
                            else:
                                ks_func.update_log([item['logId']], file)
                        start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                        if item['accountType'] == '结算账单总数':
                            bill_count = ks_func.get_bill_count(period)
                            param_list.append({'orderType': '结算账单总数', 'fileName': bill_count, 'period': period, 'logId': item['logId'], 'startTime': start_time})
                        if item['accountType'] == '运费险总数':
                            bill_count = ks_func.get_delivery_fee_count(period)
                            param_list.append({'orderType': '运费险总数', 'fileName': bill_count, 'period': period, 'logId': item['logId'], 'startTime': start_time})
                    if len(param_list) > 0:
                        # 编码字符串
                        coding_param = ks_func.encode_param(param_list)
                        # 上传文件
                        uri = "api/v1/ksBill/ksBillRPAImport/{}".format(item['storeCode'])
                        ks_func.upload_file(uri, coding_param, file_list)
                    # 直接跳出循环，因为快手系统同一个账号5分钟内只能下载一次账单
                    break
                ks_func.close()
    except:
        logger.info(traceback.format_exc())